package com.example.wn.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.alibaba.fastjson2.util.UUIDUtils;
import com.example.wn.model.vo.system.ValidateCodeVo;
import com.example.wn.service.ValidCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidCodeServiceImpl implements ValidCodeService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public ValidateCodeVo getValidCode() {
        // 宽 高 验证码个数 干扰线条数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 20);
        String codeValue = captcha.getCode();
        String image = captcha.getImageBase64();

        // 生成uuid做key
        String codeKey = UUID.randomUUID().toString().replace("-", "");

        // 存到Redis
        redisTemplate.opsForValue().set("user:login:validcode:" + codeKey, codeValue, 5, TimeUnit.MINUTES);


        // 构造结果
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        validateCodeVo.setCodeKey(codeKey);
        validateCodeVo.setCodeValue("data:image/png;base64," + image);
        return validateCodeVo;
    }
}
